package com.android.accessibility.fragment;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.MimeTypeMap;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.accessibility.R;
import com.android.accessibility.activity.VideoActivity;
import com.android.accessibility.base.BaseFragment;
import com.android.accessibility.utils.Log;
import com.android.accessibility.utils.SDCardImageLoader;
import com.android.accessibility.utils.Utils;

public class VideoFragment extends BaseFragment implements OnItemLongClickListener, OnItemClickListener, OnClickListener, OnScrollListener {

    private GridView mGridView;
    private VidoeAdapter mVidoeAdapter;
    private TextView mTitleView;
    private View mFunMenu;
    private View mDeleteFile;
    private Button mSelectView;
    private SDCardImageLoader mSDCardImageLoader;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        mSDCardImageLoader = new SDCardImageLoader(getActivity());
        View view = inflater.inflate(R.layout.video_grid_layout, null);
        View emptyView = view.findViewById(R.id.empty);
        mGridView = (GridView) view.findViewById(R.id.gridview);
        mGridView.setEmptyView(emptyView);
        mGridView.setNumColumns(3);
        mGridView.setOnItemLongClickListener(this);
        mGridView.setOnItemClickListener(this);
        mGridView.setOnScrollListener(this);

        mTitleView = (TextView) view.findViewById(R.id.title_view);
        mFunMenu = view.findViewById(R.id.fun_menu);
        mDeleteFile = view.findViewById(R.id.delete_file);
        mDeleteFile.setOnClickListener(this);
        mSelectView = (Button) view.findViewById(R.id.select_unselect);
        mSelectView.setOnClickListener(this);

        mTitleView.setText("微信视频");
        mFunMenu.setVisibility(View.GONE);
        mGridView.setChoiceMode(ListView.CHOICE_MODE_NONE);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mGridView.postDelayed(new Runnable() {
            @Override
            public void run() {
                showListView();
            }
        }, 500);
    }

    private void showListView() {
        List<File> fileList = new ArrayList<File>();
        List<String> dirs = Utils.readVideoDir(getActivity());
        for (String dir : dirs) {
            File files[] = null;
            if (!TextUtils.isEmpty(dir)) {
                File videoFile = new File(dir);
                if (videoFile.exists()) {
                    files = videoFile.listFiles(new FilenameFilter() {
                        @Override
                        public boolean accept(File dir, String filename) {
                            if (filename != null && filename.endsWith(".mp4")) {
                                return true;
                            }
                            return false;
                        }
                    });
                }
            }
            if (files != null && files.length > 0) {
                List<File> list = Arrays.asList(files);
                Utils.addAll(fileList, list);
            }
        }
        if (fileList != null && fileList.size() > 0) {
            try {
                Collections.sort(fileList, new Comparator<File>() {
                    @Override
                    public int compare(File lhs, File rhs) {
                        if (lhs == rhs) {
                            return 0;
                        } else {
                            long rLast = rhs.lastModified();
                            long lLast = lhs.lastModified();
                            return rLast > lLast ? 1 : -1;
                        }
                    }
                });
            } catch(Exception e) {
            }
            mVidoeAdapter = new VidoeAdapter(getActivity(), fileList);
            mGridView.setAdapter(mVidoeAdapter);
        } else {
            mVidoeAdapter = new VidoeAdapter(getActivity(), new ArrayList<File>());
            mGridView.setAdapter(mVidoeAdapter);
        }
        mTitleView.setText("微信视频");
        mFunMenu.setVisibility(View.GONE);
        mGridView.setChoiceMode(ListView.CHOICE_MODE_NONE);
    }

    class VidoeAdapter extends ArrayAdapter<File> {

        private Context mContext;
        public VidoeAdapter(Context context, List<File> objects) {
            super(context, 0, objects);
            mContext = context;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            int itemWidth = 0;
            int itemHeight = 0;
            int hs = Utils.dp2px(mContext, 2);
            itemWidth = (mGridView.getWidth() - 2 * hs) / 3;
            itemHeight = itemWidth;

            ViewHolder holder = null;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = LayoutInflater.from(mContext).inflate(R.layout.video_list_item, null);
                holder.imageView = (ImageView) convertView.findViewById(R.id.imageview);
                holder.maskView = convertView.findViewById(R.id.maskview);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            convertView.setLayoutParams(new AbsListView.LayoutParams(itemWidth, itemHeight));
            File file = getItem(position);
            if (file != null) {
                holder.imageView.setTag(file.getAbsolutePath());
                mSDCardImageLoader.loadVideoThumb(file.getAbsolutePath(), holder.imageView, mScrollStateChanged);
                if (mGridView.isItemChecked(position)) {
                    holder.maskView.setVisibility(View.VISIBLE);
                } else {
                    holder.maskView.setVisibility(View.INVISIBLE);
                }
            }
            return convertView;
        }

        class ViewHolder {
            View maskView;
            ImageView imageView;
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.select_unselect) {
            selectedAll(!isSelectAll());
        } else if (v.getId() == R.id.delete_file) {
            deleteSelect();
        }
    }

    private boolean isSelectAll() {
        return mGridView.getCheckedItemCount() == mGridView.getCount();
    }

    public void selectedAll(boolean select) {
        for (int i = 0; i < mVidoeAdapter.getCount(); i++) {
            mGridView.setItemChecked(i, select);
        }
        updateSelectAllText();
    }

    private void updateSelectAllText() {
        mSelectView.setText(isSelectAll() ? "反选" : "全选");
    }

    public void unSelectedAll() {
        mGridView.clearChoices();
    }

    private void deleteSelect() {
        SparseBooleanArray positions = mGridView.getCheckedItemPositions();
        if (positions == null) {
            return;
        }
        List<File> selectFileList = new ArrayList<File>();
        for (int i = 0; i < mVidoeAdapter.getCount(); i++) {
            if (positions.get(i, false)) {
                selectFileList.add(mVidoeAdapter.getItem(i));
            }
        }
        if (selectFileList != null && selectFileList.size() > 0) {
            delete(selectFileList);
        }
    }

    private void delete(final List<File> list) {
        final ProgressDialog dialog = ProgressDialog.show(getActivity(), null, "正在删除中");
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        new Thread() {
            public void run() {
                final List<File> deletedList = new ArrayList<File>();
                for (File s : list) {
                    updateProgressDialog(dialog, "正在删除 : " + s);
                    deleteFile(s);
                    deletedList.add(s);
                }
                if (getActivity() == null) {
                    return;
                }
                getActivity().runOnUiThread(new Runnable() {
                    public void run() {
                        for (File s : deletedList) {
                            mVidoeAdapter.remove(s);
                        }
                        if (dialog != null && dialog.isShowing()) {
                            dialog.dismiss();
                        }
                    }
                });
            }
        }.start();
    }

    private void deleteFile(File file) {
        if (file != null && file.exists()) {
            String filePath = file.getAbsolutePath();
            int index = filePath.lastIndexOf(".mp4");
            if (index > -1) {
                File thumbFile = new File(filePath.substring(0, index) + ".jpg");
                if (thumbFile.exists()) {
                    thumbFile.delete();
                }
            }
            file.delete();
        }
    }

    private void updateProgressDialog(final ProgressDialog dialog, final String text) {
        if (getActivity() == null) {
            return;
        }
        getActivity().runOnUiThread(new Runnable() {
            public void run() {
                if (dialog != null && dialog.isShowing()) {
                    dialog.setMessage(text);
                }
            }
        });
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
        if (mGridView.getChoiceMode() == ListView.CHOICE_MODE_MULTIPLE) {
            View maskView = view.findViewById(R.id.maskview);
            if (mGridView.isItemChecked(position)) {
                maskView.setVisibility(View.VISIBLE);
            } else {
                maskView.setVisibility(View.INVISIBLE);
            }
            updateSelectAllText();
            return;
        }
        playVideo(position);
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view,
            int position, long id) {
        showSelectionDialog(position);
        return true;
    }

    private void showSelectionDialog(final int position) {
        final File file = mVidoeAdapter.getItem(position);
        final String items[] = new String[]{"播放", "选择", "分享", "删除"};
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("菜单");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (which == 0) {
                    playVideo(position);
                } else if (which == 1) {
                    setChoice(position);
                } else if (which == 2) {
                    share(position);
                } else if (which == 3) {
                    List<File> list = new ArrayList<File>();
                    list.add(file);
                    delete(list);
                }
            }
        });
        builder.create().show();
    }

    private void playVideo(int position) {
        try {
            File file = mVidoeAdapter.getItem(position);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setClass(getActivity(), VideoActivity.class);
            intent.setData(Uri.fromFile(file));
            intent.setDataAndType(Uri.fromFile(file), getMimeType(file));
            startActivity(intent);
            getActivity().overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
        } catch(Exception e) {
            Toast.makeText(getActivity(), "无法打开该文件", Toast.LENGTH_SHORT).show();
        }
    }

    private void setChoice(int position) {
        if (mGridView.getChoiceMode() == ListView.CHOICE_MODE_NONE) {
            mGridView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
            mGridView.setItemChecked(position, true);
            mFunMenu.setVisibility(View.VISIBLE);
        }
    }

    private void share(int position) {
        final File file = mVidoeAdapter.getItem(position);
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
        intent.setType("video/*"); 
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(Intent.createChooser(intent, "分享"));
    }

    public boolean onBackPressed() {
        if (mGridView.getChoiceMode() == ListView.CHOICE_MODE_MULTIPLE) {
            mGridView.setChoiceMode(ListView.CHOICE_MODE_NONE);
            mVidoeAdapter.notifyDataSetChanged();
            mFunMenu.setVisibility(View.GONE);
            unSelectedAll();
            updateSelectAllText();
            return true;
        }
        return false;
    }

    private static String getSuffix(File file) {
        if (file == null || !file.exists() || file.isDirectory()) {
            return null;
        }
        String fileName = file.getName();
        if (fileName.equals("") || fileName.endsWith(".")) {
            return null;
        }
        int index = fileName.lastIndexOf(".");
        if (index != -1) {
            return fileName.substring(index + 1).toLowerCase(Locale.US);
        } else {
            return null;
        }
    }

    public static String getMimeType(File file) {
        String suffix = getSuffix(file);
        if (suffix == null) {
            return "file/*";
        }
        String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
                suffix);
        if (type != null && !type.isEmpty()) {
            return type;
        }
        return "file/*";
    }

    /**************************************************************************/
    // 不滑动时加载图片
    private int mStartIndex = -1;
    private int mEndIndex;
    private boolean mScrollStateChanged = false;

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        mScrollStateChanged = true;
        if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {// list停止滚动时加载图片
            pageImgLoad(mStartIndex, mEndIndex);
        }
        Log.d(Log.TAG, "mStartIndex : " + mStartIndex);
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
            int visibleItemCount, int totalItemCount) {
        mStartIndex = firstVisibleItem;
        mEndIndex = firstVisibleItem + visibleItemCount;
        if (mEndIndex >= totalItemCount) {
            mEndIndex = totalItemCount - 1;
        }
    }

    private void pageImgLoad(int startIndex, int endIndex) {
        for (; startIndex <= endIndex; startIndex++) {
            try {
                File file = mVidoeAdapter.getItem(startIndex);
                View view = mGridView.getChildAt(startIndex - mStartIndex);
                ImageView imageView = (ImageView) view.findViewById(R.id.imageview);
                imageView.setTag(file.getAbsolutePath());
                mSDCardImageLoader.loadVideoThumb(file.getAbsolutePath(), imageView);
            } catch(Exception e){
            }
        }
    }
}
